﻿

using System;
using System.Collections;
using System.Linq;
using Google.Protobuf.WellKnownTypes;
using IRepository;
using IServices;
using Senparc.CO2NET.Extensions;
using SqlSugar;
using YL.Core.Entity;
using YL.Utils.Extensions;

namespace Services
{
    public class Whr_wechat_sessionServices : BaseServices<Whr_wechat>, IWhr_wechat_sessionServices
    {
        private readonly SqlSugarClient _client;

        private readonly IWhr_wechatRepository _wechatRepository;

        public Whr_wechat_sessionServices(SqlSugarClient client, IWhr_wechatRepository repository) : base(repository)
        {
            _client = client;
            _wechatRepository = repository;
        }

        /// <summary>
        /// 获取会话信息
        /// </summary>
        /// <param name="wechatToken"></param>
        /// <returns></returns>
        public Whr_wechat Get(string wechatToken)
        {
            Whr_wechat whrWechat = _client.Queryable<Whr_wechat>().Where(s => s.WechatToken == wechatToken).First();
            return whrWechat;
        }

        /// <summary>
        /// 根据openid保持数据
        /// </summary>
        /// <param name="wechat"></param>
        /// <returns></returns>
        public int Set(Whr_wechat wechat)
        {
            if (wechat.Openid.IsNullOrEmpty()) 
            {
                return 0;
            } 
            var whrWechat = _client.Queryable<Whr_wechat>().Where(s => s.Openid == wechat.Openid).First();

            foreach (var p in wechat.GetType().GetProperties()) 
            {
                Console.WriteLine(p.Name);
                Console.WriteLine(p.GetValue(wechat));
            }

            int flag;
            if (whrWechat == null)
            {
                flag = _client.Insertable(wechat).ExecuteReturnIdentity();
            }
            else
            {
                wechat.Id = whrWechat.Id;
                wechat.UpdateTime = DateTimeExt.GetUnixTimestamp();
                flag = _client.Updateable(wechat).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
                if (flag > 0) 
                {
                    return whrWechat.Id;
                }
            }

            return flag;
        }      
    }
}
